Class Nur.MNISV3.Service.CASign Extends %RegisteredObject
{

/// 保存CA用户ID
/// deviceId=^84f2a74d81060225; status=Ok; caUserId=; userId=12177; 
ClassMethod saveCaUserId(caUserId, userId, status = "", deviceId = "") As %String [ WebMethod ]
{
    s ^TMP("saveCaUserId")=$LB(caUserId, userId,status,deviceId)
    s id=##class(Nur.PDACaUser).Save(userId,caUserId,deviceId,status)
    i id=-1 s msg="保存失败！" ,status=-1
    e  s msg="保存成功！",status=0
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt($g(msg),"msg")
    d json.SetAt("9999","msgcode")
    d json.SetAt($g(status),"status")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)
    q ret
}

/// 获取服务器当前时间
/// w ##class(Nur.MNISV3.Service.CASign).getCurDateTime()
ClassMethod GetCurDateTime() As %String [ WebMethod ]
{
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt("","msg")
    d json.SetAt("99999","msgcode")
    d json.SetAt("0","status")
    d json.SetAt(+$h,"CurDate")
    d json.SetAt($p($h,",",2),"CurTime")
    s curDateTime=$zd(+$h,3)_" "_$zt($p($h,",",2))  
    s endDateTime=$zd(+$h+1,3)_" "_$zt($p($h,",",2))
    d json.SetAt($g(curDateTime),"curDateTime")
    d json.SetAt($zd(+$h,3)_" 00:00:00","stDateTime")
    d json.SetAt($zd(+$h,3)_" 23:59:59","endDateTime")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)
    q ret
}

/// 时间是否有效
/// w ##class(Nur.MNISV3.Service.CASign).ifValidTime(65302,60451)
ClassMethod ifValidTime(date, time) As %String [ WebMethod ]
{
    s validTime="43200" //12个小时
    //s validTime="20" //2分钟
    s curDate=+$h
    s curTime=$p($h,",",2)
    s timeDvalue=curDate*86400+curTime-(date*86400)-time
    i timeDvalue>validTime s validFlag=0  //无效
    e  s validFlag=1  //有效
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt("","msg")
    d json.SetAt("99999","msgcode")
    d json.SetAt("0","status")
    d json.SetAt(validFlag,"ValidFlag")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)
    q ret
}

/// 取CA服务开关       
ClassMethod GetCAServiceStatus(LocID As %String, UserID As %String = "") As %String
{
    set $ZTRAP = "SOAPError"
    s ret=##class(CA.DigitalSignatureService).IsCACTLoc(LocID, UserID)
    ;s ret=##Class(CA.DigitalSignatureService).GetCAServiceStatus(LocID)
    q:ret'="1" 0
    ;s:UserID'="" DoctorType=##class(web.SSUser).GetDefaultCareProviderType(UserID)
    ;Q:$G(DoctorType)'="DOCTOR" 0 
    q 1
SOAPError
  quit 0
}

/// w ##class(Nur.MNISV3.Service.CASign).ExecCaSignData()
/// 医嘱执行CA签名数据
/// properties.put("mainSignTimeStamp", sheetCode + "@" + timeSaveInfo);//时间戳改成 Param参数串
/// properties.put("mainSignValue", mainSignValue);//签名信息
/// properties.put("mainSignCert", mainSignCert);//ca的唯一code
/// properties.put("ordItemsHashVal", cn.org.bjca.signet.coss.demo.utils.StringUtils.base64Decode(str));//待签信息
/// properties.put("operationType", execStaCode);//操作类型 1处理，2执行，3停止处理，4撤销处理，5撤销执行，6皮试
/// properties.put("currOrderItemStr", oeoreId);//执行记录id
ClassMethod ExecCaSignData(signID, currOrderItemStr, userId, operationType, ordItemsHashVal = "", mainSignCert = "", mainSignValue = "", mainSignTimeStamp = "", fragment = "", wardId = "") As %String [ WebMethod ]
{
    s ^GRS("ExecCaSignData1",userId_"-",currOrderItemStr,$h)=$lb(signID,currOrderItemStr,userId,operationType,ordItemsHashVal,mainSignCert,mainSignValue,mainSignTimeStamp,fragment,wardId)
    s $zt="errExecCaSignData"
    i userId["^" {
         s userCode = $p(userId,"^",1)
         s userId=$o(^SSU("SSUSR",0,"SSUSR_Initials",$$ALPHAUP^SSUTIL4(userCode),""))
    }
    //execStatusCode (F 执行，C 撤销执行，A 接受，S 完成，R 拒绝)F 执行Y 皮试阳性N 皮试阴性* C 撤销执行A 接受R 拒绝S 完成""撤销处理        
    //操作类型（S:处理、CS:撤销处理、E:执行、CE:撤销执行）
    s Type="E"
    i operationType="PDA" s Type="E"
    i operationType="F" s Type="E"
    i operationType="C" s Type="CE"
    i operationType="A" s Type="S"
    i operationType="S" s Type="S"
    i operationType="R" s Type="CS"
    i currOrderItemStr'["^" s labNo=$p($g(^OEORD(+currOrderItemStr,"I",$p(currOrderItemStr,"||",2),3)),"^",20)
    i $g(labNo)'="" s currOrderItemStr=##class(web.DHCNurSpecerNo).GetOrderStr(labNo)
    s msg=""
    // 就诊号
    s episodeId=+^OEORD(+currOrderItemStr) 
    s wardId = $p(^PAADM(episodeId),"^",70)
    s locId = $p($g(^PAWARD(wardId)),"^",5)
    s hospitalId = $p($g(^CTLOC(locId)),"^",22)
    s status=0
    s len=$l(currOrderItemStr,"^")
    f i=1:1:len {
        s ordId=$p(currOrderItemStr,"^",i)
        continue:ordId=""
        i $g(labNo)'="" s ordId=ordId_"||1"
        s ret=..InsertBatchSignRecord(signID,ordId , userId , Type , ordItemsHashVal , mainSignCert , mainSignValue,mainSignTimeStamp,hospitalId) //替换方法
        i +ret'=0 d
        .i msg="" s msg=ordId
        .e  s msg=msg_","_ordId
    }
    s json=##class(%ArrayOfDataTypes).%New()
    i msg'="" s msg=msg_"未能签名成功！" s status=-1
    e  s msg="签名成功"
    d json.SetAt($g(msg),"msg")
    d json.SetAt("9999","msgcode")
    d json.SetAt($g(status),"status")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)    
    q ret
errExecCaSignData
  s ^GRS("ExecCaSignData1","err11",currOrderItemStr)=$lb($ze,signID,currOrderItemStr,userId,operationType,fragment,wardId)
  q
}

/// 插入签名入表
/// w ##class(Nur.MNISV3.Service.CASign).InsertBatchSignRecord()
ClassMethod InsertBatchSignRecord(signID = "", newOrdIdDR As %String, userId As %String, operationType As %String = "", ordItemsHashVal As %String = "", mainSignCert As %String = "", mainSignValue As %String = "", mainSignTimeStamp As %String = "", hospitalId = "") As %String
{

    s myrtn=0
    TS
    //原文
    s BinaryText=##class(%SYSTEM.Encryption).Base64Decode(ordItemsHashVal)
    s originText= $zcvt(BinaryText,"I","UTF8") 
    //生成时间戳
    #; s mainSignTimeStamp=##Class(CA.DigitalSignatureService).SignTimeStamp(originText,"PHONE","BJCA",hospitalId) 
    s mainSignTimeStamp=##Class(CA.DigitalSignatureService).SignTimeStamp(originText,"PHONE","BJCA") 
  
    s old = ""
    i old="1" {
        s Object=##class(User.DHCNurExecSign).%New()
        s Object.SVOEOREID=newOrdIdDR   
        s Object.SVOEOREMainInfo =ordItemsHashVal
        s Object.SVOEOREMainSignCert =mainSignCert
        s Object.SVOEOREMainSignValue =mainSignValue
        s Object.SVOEOREMainSignTimeStamp =mainSignTimeStamp
        s Object.SVCreateUserDR=userId
        s Object.SVOperationType=operationType
        do Object.SVDigitalSignatureDRSetObjectId(signID)
        s Object.SVCreateDate=+$H
        s Object.SVCreateTime=$p($h,",",2)
    }else {
        // NurMp_CA.DHC_NurRecSign 表
        s Object=##class(Nur.CA.DHCNurSignVerify).%New()
        //医嘱关联 OE_OrdItem/OE_OrdExec
        s Object.SVOrderDR=newOrdIdDR   
        //医嘱主要信息原文(使用HASH数据存储)
        s Object.SVMainInfo =ordItemsHashVal
        //医嘱主要信息签名证书(仅数据签名服务器验签需要此参数,其它P7和XML都封装在签名信息中)
        s Object.SVMainSignCert =mainSignCert
        //医嘱主要信息签名信息
        s Object.SVMainSignValue =mainSignValue
        //医嘱时间戳
        s Object.SVMainSignTimeStamp =mainSignTimeStamp
        //记录创建人
        s Object.SVCreateUserDr=userId
        //操作类型（S:处理、CS:撤销处理、E:执行、CE:撤销执行）
        i operationType="PDA" s operationType="E"
        s Object.SVHandleType=operationType
        //调用类型（NUR:护士签字、DOC:医生签字）
        s Object.SVSignType="NUR"
    
        do Object.SVDigitalSignatureDrSetObjectId(signID)
        s Object.SVCreateDate=+$H
        s Object.SVCreateTime=$p($h,",",2)
    }

    
    s sc=Object.%Save()
    If ($System.Status.IsError(sc))
    {  
        TRO
        Do $System.Status.DisplayError(sc)
         s ^GRS("ExecCaSignData","err",newOrdIdDR)=userId_","_$System.Status.DisplayError(sc)
        Set myrtn = "-100"
    }else{
        TC
    }
    Q myrtn
}

/// 保存CA签名数据-护理病历
/// properties.put("mainSignValue", mainSignValue);//护理记录主要信息签名证书(仅数据签名服务器验签需要此参数,其它P7和XML都封装在签名信息中)
/// properties.put("mainSignCert", mainSignCert);//护理记录主要信息签名证书(仅数据签名服务器验签需要此参数,其它P7和XML都封装在签名信息中)
/// properties.put("RecInfosHash", cn.org.bjca.signet.coss.demo.utils.StringUtils.base64Decode(str));//护理记录主要信息原文(使用HASH数据存储)
/// properties.put("RecType", RecType);//单据类型ID
/// properties.put("EpisodeID", EpisodeID);//就诊号
/// properties.put("recId", recId);//记录id
/// w ##class(Nur.MNISV3.Service.CASign).RecordCaSignData()
ClassMethod RecordCaSignData(signID = "", EpisodeID As %String, userId As %String, operationType As %String, ordItemsHashVal As %String, mainSignCert As %String, mainSignValue As %String, mainSignTimeStamp = "", recId = "", wardId = "") As %String [ WebMethod ]
{
    s msg=""
    s status=""
    s $zt="errRecordCaSignData"
    s ^GRS("recordCaSignData",userId_"-"_$h)=$lb(signID,EpisodeID , userId , operationType , ordItemsHashVal, mainSignCert , mainSignValue,mainSignTimeStamp,recId,wardId)
    i userId["^" {
         s userCode = $p(userId,"^",1)
         s userId=$o(^SSU("SSUSR",0,"SSUSR_Initials",$$ALPHAUP^SSUTIL4(userCode),""))
    }
    ;s ret=##class(web.DHCNurCASignVerify).InsertNurRecBatchSign(EpisodeID , userId , RecType , RecInfosHash,mainSignCert, mainSignCert , mainSignValue,"","")
    
    ;s ret=##class(web.DHCNurSignVerify).InsertNurRecBatchSign(EpisodeID,userId,RecType,RecInfosHash, mainSignCert , mainSignValue,"")
    
    //老
    ;(EpisodeID , UserID , RecType , RecInfoHash , MainSignCert , MainSignValue, MainSignTimeStamp As %String = "", ExpStr As %String = "") As %String
    //s ret=..InsertRecSign(EpisodeID,userId,operationType,ordItemsHashVal,mainSignCert,mainSignValue,mainSignTimeStamp,"PDA",signID,recId)
    //新
    s ret=..InsertRecSign2(EpisodeID,userId,operationType,ordItemsHashVal,mainSignCert,mainSignValue,mainSignTimeStamp,"PDA",signID,recId)
    s status=0
    i ret'=0 {
         s msg=msg_"未能签名成功！", status="-1"
    }else{
         s msg="签成功"
         /*
         
         s objCurrent=##class(NurMp.DHCTempMultData).%OpenId(recId)
         s emrCode=objCurrent.EmrCode
         //w ##class(NurMp.Template).GetIndentity("EA0E756B2C654F13BC00B0DC40C5D70E")
         //科室
        s locId = $p($g(^PAWARD(wardId)),"^",5)
        s hospitalId = $p($g(^CTLOC(locId)),"^",22)
        s TemplateId=$o(^NurMp.TemplateI("TCIndentity"," "_$ZConvert(emrCode,"U"),""))
        s TemplateObj=##class(NurMp.Template).%OpenId(TemplateId)
        s HospitalID=TemplateObj.HospitalID
        s PrintTemplateIdentity= ##class(NurMp.Print.Comm).GetPicPrnCode(emrCode,HospitalID)
        i PrintTemplateIdentity="" s PrintTemplateIdentity= ##class(NurMp.Print.Comm).GetPicPrnCode(emrCode)
        w PrintTemplateIdentity,"-",emrCode,"-",HospitalID,!
        s ret=##class(NurMp.Template.MultData).MakePicture(PrintTemplateIdentity,"true",EpisodeID,"1",recId,"{""LOGON.CTLOCID"":"""_locId_""",""LOGON.GROUPDESC"":""住院护士"",""LOGON.USERID"":"""_userId_""",""LOGON.WARDID"":"""_wardId_"""}")
        //ClassMethod MakePicture(PrintTemplateIdentity, UpdateGreatePic, EpisodeId, CAFlag, Id, SessionValue)
        s ^PDA("123",EpisodeID_"-"_$h)=ret
        //后台服务生成html痕迹
        //s ret2=##class(NurMp.Template.MultData).MakeHtml(PrintTemplateIdentity,"true",EpisodeID,"1",recId,"{""LOGON.CTLOCID"":"""_locId_""",""LOGON.GROUPDESC"":""住院护士"",""LOGON.USERID"":"""_userId_""",""LOGON.WARDID"":"""_wardId_"""}")
        //s ^PDA("123",1,EpisodeID_"-")=ret2
        
        */
    }
    s json=##class(%ArrayOfDataTypes).%New()
    d json.SetAt($g(msg),"msg")
    d json.SetAt($g(ret),"ret")
    d json.SetAt("9999","msgcode")
    d json.SetAt($g(status),"status")
    s ret=##class(Nur.MNISV3.Common.JSON).Encode(json)
    q ret
errRecordCaSignData
  s ^PDAErr($h)=$ze
  q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson($ze,"","-1")
}

/// 插入签名入表-护理病历
/// w ##class(Nur.MNISV3.Service.CASign).InsertRecSign()
ClassMethod InsertRecSign(EpisodeID As %String, UserID As %String, RecType As %String = "", RecInfoHash As %String = "", MainSignCert As %String = "", MainSignValue As %String = "", MainSignTimeStamp As %String = "", ExpStr As %String = "", ID As %String = "", NurRecId As %String = "") As %String
{
    s ^TMP("InsertRecSign",1)=EpisodeID
    s ^TMP("InsertRecSign",2)=UserID
    s ^TMP("InsertRecSign",3)=RecType
    s ^TMP("InsertRecSign",4)=RecInfoHash
    s ^TMP("InsertRecSign",5)=MainSignCert
    s ^TMP("InsertRecSign",6)=MainSignValue
    s ^TMP("InsertRecSign",7)=MainSignTimeStamp
    s ^TMP("InsertRecSign",7)=NurRecId
    s myrtn=0
    TS
    s Object=##class(User.DHCNurRecSign).%New()
    s Object.SVDigitalSignatureId=ID
    s Object.SVNurRecId=NurRecId
    s Object.SVEpisodeID=EpisodeID
    s Object.SVRecMainInfo =RecInfoHash
    s Object.SVRecMainSignCert =MainSignCert
    s Object.SVRecMainSignValue =MainSignValue
    s Object.SVRecMainSignTimeStamp =MainSignTimeStamp
    s Object.SVRecType=RecType
    s Object.SVCreateUserDR=UserID
    s Object.SVCreateD=+$h
    s Object.SVCreateT=$p($h,",",2)
    
    s sc=Object.%Save()
    If ($System.Status.IsError(sc))
    {   
        TRO
        Do $System.Status.DisplayError(sc)
        Set myrtn = "-100"
    }else{
        TC
    }
    Q myrtn
}

/// 插入签名入表-护理病历
/// w ##class(Nur.MNISV3.Service.CASign).InsertRecSign()
ClassMethod InsertRecSign2(EpisodeID As %String, UserID As %String, RecType As %String = "", RecInfoHash As %String = "", MainSignCert As %String = "", MainSignValue As %String = "", MainSignTimeStamp As %String = "", ExpStr As %String = "", ID As %String = "", NurRecId As %String = "") As %String
{
    ;1.得到医嘱相关的主要信息,其它信息
    ;2.将数据组织成XML格式
    ;3.插入到User.DHCDocSignVerify
    ;4.ExpStr="StopUser_$C(1)_Info_$C(1)_OtherSignCert_$C(1)_OtherSignValue_$C(2)_UpdateUser_$C(1)_Info_$C(1)_OtherSignCert_$C(1)_OtherSignValue_$C(4)_Other"
    ;"OSVSignResTypeDR_$C(1)_OSVInfo_$C(1)_OSVSignCert_$C(1)_OSVSignValue_$C(2)_OSVSignResTypeDR_$C(1)_OSVInfo_$C(1)_OSVSignCert_$C(1)_OSVSignValue_$C(4)_Other"

    ;w ##Class(web.DHCDocSignVerify).Insert() 
    s ^TMPPDA("InsertRecSign",0)=NurRecId
    s ^TMPPDA("InsertRecSign",1)=EpisodeID
    s ^TMPPDA("InsertRecSign",2)=UserID
    s ^TMPPDA("InsertRecSign",3)=RecType
    s ^TMPPDA("InsertRecSign",4)=RecInfoHash
    s ^TMPPDA("InsertRecSign",5)=MainSignCert
    s ^TMPPDA("InsertRecSign",6)=MainSignValue
    s ^TMPPDA("InsertRecSign",7)=MainSignTimeStamp
    s ^TMPPDA("InsertRecSign",8)=NurRecId
    /*
    s newOrdIdDR=^TMP("InsertSignRecord",1)
    s UserID=^TMP("InsertSignRecord",2)
    s OperationType=^TMP("InsertSignRecord",3)
    s OEORIItemHash=^TMP("InsertSignRecord",4)
    s MainSignCert=^TMP("InsertSignRecord",5)
    s MainSignValue=^TMP("InsertSignRecord",6)
    s MainSignTimeStamp=^TMP("InsertSignRecord",7)
    */
    s wardID = $p(^PAADM(EpisodeID),"^",70)
    s locId = $p($g(^PAWARD(wardId)),"^",5)
    s hospitalId = $p($g(^CTLOC(locId)),"^",22)
    //PC护理病历 提供获取的xml原文数据
    //s xml=##class(Nur.Interface.OutSide.EmrFiling).getRecMainXML(NurRecId)
    //原文
    s BinaryText=##class(%SYSTEM.Encryption).Base64Decode(RecInfoHash)
    s originText= $zcvt(BinaryText,"I","UTF8") 
    //生成时间戳
    s MainSignTimeStamp=##Class(CA.DigitalSignatureService).SignTimeStamp(originText,"PHONE","BJCA",hospitalId) 
    //s MainSignTimeStamp=##class(CA.Adapter.BJCA.PhoneHttp).CreateTimeStamp()
    s myrtn=0
    ;其它信息,需循环此变量插入到属性
    ;s OtherSignRecord=$p(ExpStr,$C(4),1)
    TS
    s rowid="" //表 NurMp_CA.DHC_NurRecSign
    s rowid=$o(^NurMp.CA.DHCNurRecSignI("RecId"," "_NurRecId,rowid))
    i rowid'="" s Object=##class(NurMp.CA.DHCNurRecSign).%OpenId(rowid)
    e  s Object=##class(NurMp.CA.DHCNurRecSign).%New() 
    s Object.SVDigitalSignatureId=ID  
    s Object.SVNurRecId=NurRecId
    s Object.SVEpisodeID=EpisodeID
    s Object.SVRecMainInfo =RecInfoHash //主要信息原文(使用HASH数据存储)
    s Object.SVRecMainSignCert =MainSignCert
    s Object.SVRecMainSignValue =MainSignValue //主要信息签名信息
    s Object.SVRecMainSignTimeStamp =MainSignTimeStamp
    s Object.SVRecType=RecType
    s Object.SVCreateUserDR=UserID
    s Object.SVCreateD=+$h
    s Object.SVCreateT=$p($h,",",2)
    s sc=Object.%Save()
    If ($System.Status.IsError(sc))
     {   
        TRO
        Do $System.Status.DisplayError(sc)
        Set myrtn = "-100"
     }else{
        TC
     }
    Q myrtn
}

}
